package com.AEWMS.Servlet.util;

import com.AEWMS.Dao.Attendance;
import com.AEWMS.Service.AttendanceWarningService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author ths
 * @create 2021/4/24 20:44
 */
@WebServlet(name = "BatchImport", urlPatterns = "/BatchImport")
public class BatchImport extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        char[] buf = new char[1024];
        int len;
        while ((len = reader.read(buf)) != -1){
            sb.append(buf,0,len);
        }
        String sheet = sb.toString();
        JSONObject object = JSON.parseObject(sheet);
        JSONArray ja = JSONArray.parseArray(object.getString("file"));
        ArrayList<Attendance> aa = new ArrayList<>();
        for (int i = 0; i < ja.size(); i++){
            JSONObject job = ja.getJSONObject(i);
            Attendance a = new Attendance();
            a.setWeek(job.get("周数").toString());
            a.setSemester(job.get("学期").toString());
            a.setStudentNumber(job.get("学号").toString());
            if (job.get("备注") != null){
                a.setAttendanceNote(job.get("备注").toString());
            }
            a.setAttendanceTimes(Integer.parseInt(job.get("考勤次数").toString()));
            a.setAttendanceTypeId(job.get("考勤类型id").toString());
            aa.add(a);
        }
        System.out.println(aa.toString());
        AttendanceWarningService s  = new AttendanceWarningService();
        int count = 0;
        for (Attendance attendance : aa) {
            if (s.insertAttend(attendance)){
                count++;
            }
        }
        response.getWriter().println(JSON.toJSONString("成功新增"+count+"条数据"));
    }
}
